package com.limoyu.unityTest;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.unity3d.player.UnityPlayerActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOError;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainActivity extends UnityPlayerActivity {

    private static final int PHOTO_REQUEST_CODE = 1;//相册
    public static final int PHOTOHRAPH = 2;// 拍照
    public static final int PHOTORESULT=3;//结果
    public static final int NONE = 0;
    private  Uri m_CropImageUri;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Activity","Main Activity启动");
    }



    /**
     * Toast显示unity发送过来的内容
     * @param content           消息的内容
     * @return                  调用是否成功
     */
    public void ShowToast(String content){
        Toast.makeText(getApplicationContext(),"From Activity",Toast.LENGTH_SHORT).show();
    }

    public void Vibrator(int val)
    {
        Vibrator vibrator = (Vibrator)this.getSystemService(this.VIBRATOR_SERVICE);
        vibrator.vibrate(val);
    }


    //调用镜头
    public void OpenCamera()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
        startActivityForResult(intent, PHOTOHRAPH);
    }

    public  void SaveBitMap(Bitmap bitMap) throws IOError
    {
        if(null==bitMap)
        {
            Log.i("Unity","SaveBitmap=>bitmap为null");
        }
        FileOutputStream fout = null;
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
        path+="/image.jpg";
        try {
            File destDir =new File(path);
            if(!destDir.exists())
                destDir.mkdir();

            fout=new FileOutputStream(path);

        } catch (Exception e) {
            e.printStackTrace();
        }

        bitMap.compress(Bitmap.CompressFormat.JPEG,100,fout);
        
        try {
            fout.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        try {
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        callUnity("Main Camera","OnImagePath", path);
    }

    //调用相册
    public void OpenGallery()
    {
        Intent intent = new Intent(Intent.ACTION_PICK,null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
        startActivityForResult(intent, PHOTO_REQUEST_CODE);
        Log.d("Activity","打开相册");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == NONE){
            return;
        }

        if(requestCode==PHOTO_REQUEST_CODE){
            if(data == null){
                return;
            }
            Uri uri = data.getData();
            //String imagePath = getImagePath(uri);
            //Log.d("Activity","获取图片路径"+imagePath);
            //callUnity("Main Camera","GetPhoto", imagePath);
            Log.d("Activity","开始图片剪切");
            startPhotoZoom(data.getData());
        }

        if(requestCode == PHOTORESULT)
        {
            try {
                Log.d("Activity","缩放照片完毕");
                Bitmap hadeShot = BitmapFactory.decodeStream(getContentResolver().openInputStream(m_CropImageUri));
                Log.d("Activity","获取位图");
                SaveBitMap(hadeShot);
                Log.d("Activity","保存位图");

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        if (requestCode == PHOTOHRAPH) {
            String path = Environment.getExternalStorageDirectory() + "/temp.jpg";
            Log.d("Activity","获取图片路径"+path);
            callUnity("Main Camera","GetPhoto", path);
        }
    }

    public void startPhotoZoom(Uri uri) {
        if (null == uri) {
            Log.d("Activity","图片为null");
            return;
        }

        //剪裁图片文件
        File cropPhoto = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "crop_image.jpg");
        //File cropPhoto = new File(getExternalCacheDir(), "crop_image.jpg");
        Log.d("Activity","创建剪切文件");
        try {
            if (cropPhoto.exists()) {
                cropPhoto.delete();
            }
            cropPhoto.createNewFile();
            Log.d("Activity","剪切文件创建成功");

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("Activity","剪切文件创建失败");
        }

        m_CropImageUri = Uri.fromFile(cropPhoto);
        Log.d("Activity","裁剪图片路径:"+m_CropImageUri.toString());
        //m_CropImageUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/"+"crop_image.jpg");
        //m_CropImageUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.Limoyu.UnityToAndroid/cache/" + "crop_image.jpg");
        //Log.d("Activity","裁剪图片路径更改为:"+m_CropImageUri.toString());
        //打开系统得剪切窗体
        Log.d("Activity","剪切窗口参数设置准备");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//动态授权
        intent.putExtra("crop","true");
        intent.putExtra("scale","true");
        intent.putExtra("outputX","300");
        intent.putExtra("outputY", "300");
        intent.putExtra("return-data",false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,m_CropImageUri);
        intent.putExtra("noFaceDetection",true);
        Log.d("Activity","剪切窗口参数设置完成");
        try {
            Log.d("Activity","打开剪切页面");
            startActivityForResult(intent,PHOTORESULT);
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();

        }

    }

    /**
     * 调用Unity的方法
     * @param gameObjectName    调用的GameObject的名称
     * @param functionName      方法名
     * @param args              参数
     * @return                  调用是否成功
     */
    boolean callUnity(String gameObjectName, String functionName, String args){
        try {
            Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
            Method method =classtype.getMethod("UnitySendMessage", String.class,String.class,String.class);
            method.invoke(classtype,gameObjectName,functionName,args);
            return true;
        } catch (ClassNotFoundException e) {

        } catch (NoSuchMethodException e) {

        } catch (IllegalAccessException e) {

        } catch (InvocationTargetException e) {

        }
        return false;
    }

    private String getImagePath(Uri uri)
    {

        if(null == uri) return null;
        String path = null;
        final String scheme = uri.getScheme();
        if (null == scheme) {
            path = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            path = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(uri, proj, null, null,
                    null);
            int nPhotoColumn = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (null != cursor) {
                cursor.moveToFirst();
                path = cursor.getString(nPhotoColumn);
            }
            cursor.close();
        }
        return path;
    }

}
